package com.haredot.security;

import com.github.hiwepy.qqwry.spring.boot.ext.QQWry;
import com.haredot.entity.SignInLog;
import com.haredot.properties.JwtProperties;
import com.haredot.utils.JwtUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录成功后执行的代码
 */
public class HaredotAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    private JwtProperties jwtProperties ;

    private RabbitTemplate rabbitTemplate ;

    private QQWry qqWry ;

    public HaredotAuthenticationSuccessHandler(JwtProperties jwtProperties, RabbitTemplate rabbitTemplate, QQWry qqWry) {
        this.jwtProperties = jwtProperties;
        this.rabbitTemplate = rabbitTemplate ;
        this.qqWry = qqWry ;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        UserDetails principal = (UserDetails)authentication.getPrincipal();

        SignInLog.sendLog(request, qqWry, rabbitTemplate, authentication.getName(), true, null);

        JwtUtils.generatorToken(principal, jwtProperties, response, true , true);
    }

}
